package com.lenovo.smarttraffic.ui.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.api.VolleyCallBack;
import com.lenovo.smarttraffic.bean.GsonBean.SenseBean;
import com.lenovo.smarttraffic.bean.GsonBean.WeatherInfoBean;
import com.lenovo.smarttraffic.util.VolleyUtil;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;


/**
 * @author Amoly
 * @date 2019/4/11.
 * description：主页面
 */
public class MainContentFragment extends BaseFragment {
    PieChart mMPieChat;

    TextView mTvTemp;
    TextView mTvDetail;
    ImageView mIvDetail;
    TextView mTvTempTom;
    TextView mTvDetailTom;
    ImageView mIvDetailTom;

    TextView mTvLightDetail;
    TextView mTvSportDetail;
    TextView mTvWearDetail;
    TextView mTvColdDetail;

    TextView mTvMetro;
    TextView mTvBuy;
    TextView mTvUser;
    TextView mTvUserManager;
    private Timer timer;
    private TimerTask task1;
    private TimerTask task2;

    private SenseBean senseBean;
    private WeatherInfoBean weatherInfoBean;
    private List<WeatherInfoBean.ROWSDETAILBean> mlist;
    private Integer[] colors = new Integer[]{
            Color.rgb(152, 50, 0),
            Color.rgb(57, 205, 8)
    };
    private static MainContentFragment instance = null;
    private static final String TAG = "MainContentFragment";

    public static MainContentFragment getInstance() {
        if (instance == null) {
            instance = new MainContentFragment();
        }
        return instance;
    }


    @Override
    protected View getSuccessView() {
        View convertView = View.inflate(getActivity(), R.layout.fragment_home, null);
        mMPieChat = convertView.findViewById(R.id.mPieChat);
        mTvTemp = convertView.findViewById(R.id.tv_temp);
        mTvDetail = convertView.findViewById(R.id.tv_detail);
        mIvDetail = convertView.findViewById(R.id.iv_detail);
        mTvTempTom = convertView.findViewById(R.id.tv_temp_tom);
        mTvDetailTom = convertView.findViewById(R.id.tv_detail_tom);
        mIvDetailTom = convertView.findViewById(R.id.iv_detail_tom);
        mTvTemp.setOnClickListener(this);
        mTvTempTom.setOnClickListener(this);

        mTvLightDetail = convertView.findViewById(R.id.tv_light_detail);
        mTvSportDetail = convertView.findViewById(R.id.tv_sport_detail);
        mTvWearDetail = convertView.findViewById(R.id.tv_wear_detail);
        mTvColdDetail = convertView.findViewById(R.id.tv_cold_detail);

        mTvMetro = convertView.findViewById(R.id.tv_metro);
        mTvMetro.setOnClickListener(this);
        mTvBuy = convertView.findViewById(R.id.tv_buy);
        mTvBuy.setOnClickListener(this);
        mTvUser = convertView.findViewById(R.id.tv_user);
        mTvUser.setOnClickListener(this);
        mTvUserManager = convertView.findViewById(R.id.tv_user_manager);
        mTvUserManager.setOnClickListener(this);
        return convertView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        timer = new Timer();

    }

    private void initChat() {
        mMPieChat.setDrawHoleEnabled(true);
        mMPieChat.setHoleColor(Color.WHITE);
        mMPieChat.setHoleRadius(70f);
        mMPieChat.setDrawCenterText(true);
        mMPieChat.setCenterTextSize(10f);
        Description description = mMPieChat.getDescription();
        description.setEnabled(false);
        Legend legend = mMPieChat.getLegend();
        legend.setEnabled(false);
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    getAllSense();
                    break;
                case 2:
                    drawchat();
                    reFreshPage();
                    break;
                case 3:
                    getWeather();
                    break;
                case 4:
                    handlerWeather();
                    break;
            }
            return false;
        }
    });

    private void handlerWeather() {
        mTvTemp.setText("今日天气 " + weatherInfoBean.getWCurrent() + "°");
        mTvDetail.setText(mlist.get(1).getType());
        mTvTempTom.setText("明日天气 " + mlist.get(2).getTemperature() + "°");
        mTvDetailTom.setText(mlist.get(2).getType());
        mIvDetail.setImageResource(getWeatherType(mlist.get(1).getType()));
        mIvDetailTom.setImageResource(getWeatherType(mlist.get(2).getType()));

    }

    private Integer getWeatherType(String type) {
        switch (type) {
            case "晴":
                return R.mipmap.sun;
            case "阴":
                return R.mipmap.cloudy_;
            case "小雨":
                return R.mipmap.rain;
            default:
                return R.mipmap.cloudy;

        }
    }

    private void getWeather() {
                    VolleyUtil.post("GetWeather.do", new JSONObject(), new VolleyCallBack() {
                        @Override
                        public void onSucceess(JSONObject jsonObject, String response) {
                            weatherInfoBean = new Gson().fromJson(response, WeatherInfoBean.class);
                            if (weatherInfoBean.getRESULT().equals("S")) {
                                mlist = weatherInfoBean.getROWS_DETAIL();
                                Message message = new Message();
                                message.what = 4;
                                handler.sendMessage(message);
                            }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    private void reFreshPage() {
        if (senseBean.getLightIntensity() > 3000) {
            mTvLightDetail.setText("强");
            mTvLightDetail.setTextColor(Color.rgb(255, 0, 0));
        } else if (senseBean.getLightIntensity() >= 1000) {
            mTvLightDetail.setText("中等");
            mTvLightDetail.setTextColor(Color.rgb(0, 176, 80));
        } else {
            mTvLightDetail.setText("弱");
            mTvLightDetail.setTextColor(Color.rgb(68, 114, 196));
        }
        if (senseBean.getCo2() > 6000) {
            mTvSportDetail.setText("较不宜");
            mTvSportDetail.setTextColor(Color.rgb(129, 73, 172));
        } else if (senseBean.getCo2() >= 300) {
            mTvSportDetail.setText("中");
            mTvSportDetail.setTextColor(Color.rgb(255, 192, 0));
        } else {
            mTvSportDetail.setText("适宜");
            mTvSportDetail.setTextColor(Color.rgb(68, 220, 104));
        }
        if (senseBean.getTemperature() >= 35) {
            mTvWearDetail.setText("热");
            mTvWearDetail.setTextColor(Color.rgb(255, 0, 0));
        } else if (senseBean.getTemperature() > 21) {
            mTvWearDetail.setText("温暖");
            mTvWearDetail.setTextColor(Color.rgb(68, 220, 104));
        } else if (senseBean.getTemperature() >= 12) {
            mTvWearDetail.setText("舒适");
            mTvWearDetail.setTextColor(Color.rgb(146, 208, 80));
        } else {
            mTvWearDetail.setText("冷");
            mTvWearDetail.setTextColor(Color.rgb(52, 98, 244));
        }
        if (senseBean.getHumidity() >= 50) {
            mTvColdDetail.setText("少发");
            mTvColdDetail.setTextColor(Color.rgb(255, 255, 64));
        } else {
            mTvColdDetail.setText("较易发");
            mTvColdDetail.setTextColor(Color.rgb(255, 0, 0));
        }
    }

    private void drawchat() {

        if (senseBean.get_$Pm25270() < 35) {
            mMPieChat.setCenterText("优");
            mMPieChat.setCenterTextColor(Color.parseColor("#44dc68"));
        } else if (senseBean.get_$Pm25270() <= 75) {
            mMPieChat.setCenterText("良");
            mMPieChat.setCenterTextColor(Color.parseColor("#92d050"));
        } else if (senseBean.get_$Pm25270() < 115) {
            mMPieChat.setCenterText("轻度污染");
            mMPieChat.setCenterTextColor(Color.parseColor("#ffff40"));
        } else if (senseBean.get_$Pm25270() <= 150) {
            mMPieChat.setCenterText("中度污染");
            mMPieChat.setCenterTextColor(Color.parseColor("#bf9000"));
        } else {
            mMPieChat.setCenterText("重度污染");
            mMPieChat.setCenterTextColor(Color.parseColor("#993300"));
        }
        ArrayList<PieEntry> pieEntries = new ArrayList<>();
        pieEntries.add(new PieEntry(senseBean.get_$Pm25270()));
        //115时各站50%
        pieEntries.add(new PieEntry(115f));
        PieDataSet pieDataSet = new PieDataSet(pieEntries, "");
        pieDataSet.setColors(Arrays.asList(colors));
        PieData pieData = new PieData(pieDataSet);
        pieData.setDrawValues(false);
        mMPieChat.setData(pieData);
        mMPieChat.invalidate();
    }

    private void getAllSense() {
        VolleyUtil.post("GetAllSense.do", new JSONObject(), new VolleyCallBack() {
            @Override
            public void onSucceess(JSONObject jsonObject, String response) {
                if (jsonObject.optString("RESULT").equals("S")) {
                    senseBean = new Gson().fromJson(response, SenseBean.class);
                    Message message = new Message();
                    message.what = 2;
                    handler.sendMessage(message);
                }
            }

            @Override
            public void onFailure(String onError) {

            }
        });
    }

    @Override
    protected Object requestData() {
        return Constant.STATE_SUCCEED;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.tv_metro:
//                checkLogin(com.lenovo.smarttraffic.ui.activity.MetroSearchActivity.class);
//                break;
            case R.id.tv_user:
                checkLogin(com.lenovo.smarttraffic.ui.activity.UserMangerActivity.class);
                break;
//            case R.id.tv_user_manager:
//                checkLogin(com.lenovo.smarttraffic.ui.activity.UserInfoWebActivity.class);
//                break;
//            case R.id.tv_buy:
//                checkLogin(com.lenovo.smarttraffic.ui.activity.MapActivity.class);
//                break;
            case R.id.tv_temp :
            case R.id.tv_temp_tom:
                checkLogin(com.lenovo.smarttraffic.ui.activity.CreateWeatherActivity.class);
                break;
        }
    }

    private void checkLogin(Class<?> clazz) {
        if (MainActivity.isLogin()) {
            Intent intent = new Intent(getActivity(), clazz);
            startActivity(intent);
        } else {
            Toast.makeText(getActivity(), "请登录后查看", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        task1 = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        };
        task2 = new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 3;
                handler.sendMessage(message);
            }
        };
        timer.schedule(task1, 0, 3000);
        timer.schedule(task2, 0, 3000);
        initChat();
    }

    @Override
    public void onPause() {
        super.onPause();
        task1.cancel();
        task2.cancel();
        task1 = null;
        task2 = null;
        timer.purge();
    }

    @Override
    public void onDestroy() {
        if (instance != null) {
            instance = null;
        }
        timer.cancel();
        super.onDestroy();
    }

}
